const Controller = require('egg').Controller;

class AgentController extends Controller {
  // 新增agent接口
  async create() {
    const { ctx } = this;
    const agentData = ctx.request.body;
    try {
      const Agent = ctx.model.Agent;
      const newAgent = await Agent.create({ ...agentData, canDelete: true, count: 0, isFavorite: false });
      // 新增接口由于不涉及分页，totalPage 设为 1
      ctx.body = { success: true, data: newAgent, total: 1, page: 1, limit: 1, totalPage: 1 };
    } catch (error) {
      ctx.body = { success: false, error: error.message };
    }
  }
  // 删除agent接口
  async delete() {
    const { ctx } = this;
    const agentId = ctx.params.id;
    try {
      const Agent = ctx.model.Agent;
      const agent = await Agent.findById(agentId);
      if (agent && !agent.canDelete) {
        ctx.body = { success: false, message: '该agent不能删除', total: 0, page: 1, limit: 1, totalPage: 1 };
        return;
      }
      const deletedAgent = await Agent.findByIdAndDelete(agentId);
      if (deletedAgent) {
        ctx.body = { success: true, data: deletedAgent, total: 1, page: 1, limit: 1, totalPage: 1 };
      } else {
        ctx.body = { success: false, message: 'Agent not found', total: 0, page: 1, limit: 1, totalPage: 1 };
      }
    } catch (error) {
      ctx.body = { success: false, error: error.message };
    }
  }
  // 修改agent接口
  async update() {
    const { ctx } = this;
    const agentId = ctx.params.id;
    const updateData = ctx.request.body;
    try {
      const Agent = ctx.model.Agent;
      const agent = await Agent.findById(agentId);
      if (agent && !agent.canDelete) {
        ctx.body = { success: false, message: '该agent不能编辑', total: 0, page: 1, limit: 1, totalPage: 1 };
        return;
      }
      const updatedAgent = await Agent.findByIdAndUpdate(agentId, updateData, { new: true });
      if (updatedAgent) {
        ctx.body = { success: true, data: updatedAgent, total: 1, page: 1, limit: 1, totalPage: 1 };
      } else {
        ctx.body = { success: false, message: 'Agent not found', total: 0, page: 1, limit: 1, totalPage: 1 };
      }
    } catch (error) {
      ctx.body = { success: false, error: error.message };
    }
  }
  // 查询agent接口
  async get() {
    const { ctx } = this;
    const agentId = ctx.params.id;
    try {
      const Agent = ctx.model.Agent;
      const agent = await Agent.findById(agentId);
      if (agent) {
        ctx.body = { success: true, data: agent, total: 1, page: 1, limit: 1, totalPage: 1 };
      } else {
        ctx.body = { success: false, message: 'Agent not found', total: 0, page: 1, limit: 1, totalPage: 1 };
      }
    } catch (error) {
      ctx.body = { success: false, error: error.message };
    }
  }
  // 查询所有agent接口
  async getAll() {
    const { ctx } = this;
    const page = parseInt(ctx.query.page) || 1;
    const limit = parseInt(ctx.query.limit) || 6;
    const skip = (page - 1) * limit;
    const type = ctx.query.type;
    const query = {};
    if (type) {
      query.type = type;
    }
    try {
      const Agent = ctx.model.Agent;
      const agents = await Agent.find(query).skip(skip).limit(limit);
      const total = await Agent.countDocuments(query);
      const totalPage = Math.ceil(total / limit);
      ctx.body = { success: true, data: agents, total, page, limit, totalPage };
    } catch (error) {
      ctx.body = { success: false, error: error.message };
    }
  }
  // 搜索agent接口
  async search() {
    const { ctx } = this;
    const keyword = ctx.query.keyword;
    const type = ctx.query.type;
    const page = parseInt(ctx.query.page) || 1;
    const limit = parseInt(ctx.query.limit) || 6;
    const skip = (page - 1) * limit;
    const query = {
      $or: [
        { title: { $regex: keyword, $options: 'i' } },
        { description: { $regex: keyword, $options: 'i' } }
      ]
    };
    if (type) {
      query.type = type;
    }
    try {
      const Agent = ctx.model.Agent;
      const agents = await Agent.find(query).skip(skip).limit(limit);
      const total = await Agent.countDocuments(query);
      const totalPage = Math.ceil(total / limit);
      ctx.body = { success: true, data: agents, total, page, limit, totalPage };
    } catch (error) {
      ctx.body = { success: false, error: error.message };
    }
  }
  // 查询所有收藏的 agent 列表
  async getFavoriteAgents() {
    const { ctx } = this;
    const page = parseInt(ctx.query.page) || 1;
    const limit = parseInt(ctx.query.limit) || 6;
    const skip = (page - 1) * limit;
    try {
      const Agent = ctx.model.Agent;
      const favoriteAgents = await Agent.find({ isFavorite: true }).skip(skip).limit(limit);
      const total = await Agent.countDocuments({ isFavorite: true });
      const totalPage = Math.ceil(total / limit);
      ctx.body = { success: true, data: favoriteAgents, total, page, limit, totalPage };
    } catch (error) {
      ctx.body = { success: false, error: error.message };
    }
  }
  // 轮播图接口，返回 3 张图片 URL
  async getCarouselImages() {
    const { ctx } = this;
    try {
      ctx.body = { success: true, data: ['https://gitee.com/zyy1573/picgo/raw/master/WX20250421-083907@2x.png', 'https://gitee.com/zyy1573/picgo/raw/master/WX20250421-083845@2x.png', 'https://gitee.com/zyy1573/picgo/raw/master/WX20250421-083918@2x.png'] };
    } catch (error) {
      ctx.body = { success: false, error: error.message };
    }
  }

  // about接口
  async getAbout() {
    const { ctx } = this;
    try {
      ctx.body = {
        success: true, data: [{
          title: '全新上线「本地文件问答」',
          tag: '电脑版',
          content: 'Windows 用户通过设置页进入「本地文件问答」选项后，可下载模型至本地设备。你可以在离线状态下，针对本地文件进行 AI 问答。所有数据均不会上传到云端，为你的隐私提供全方位保护。',
          image: 'https://p3-flow-imagex-sign.byteimg.com/ocean-cloud-tos/image_generation/fcf53542ae83c4756216ff96b2e4141f_1745409923448154117.png~tplv-a9rns2rl98-image.png?rk3s=25bff839&x-expires=1776945923&x-signature=6NPvaJmsk4OYjO1%2ByqXZVhS%2BVpU%3D',
          date: '2025年4月22日'
        }, {
          title: '「AI 阅读」支持设置页面宽度',
          tag: '',
          content: '阅读文件时，可以智能调节页面尺寸，只需轻点选项，文件即可自动适应屏幕宽高，带来更顺畅的阅读体验。',
          image: 'https://p9-flow-imagex-sign.byteimg.com/ocean-cloud-tos/image_generation/be2b00f48fb2b923b2cc0fc33f186468_1745388692252718821.png~tplv-a9rns2rl98-image.png?rk3s=25bff839&x-expires=1776924692&x-signature=uZVF7qymIHTrgsZ9TK%2Bsu95%2Bdl0%3D',
          date: '2025年4月11日'
        }, {
          title: '新标签页支持开启「深度思考」',
          tag: '电脑版',
          content: '在新标签页输入框进行提问时，支持打开「深度思考」，获取更全面精准的回复效果。',
          image: 'https://p9-flow-imagex-sign.byteimg.com/ocean-cloud-tos/image_generation/6a56708d8cf425c6fcf1522fad7db3e1_1745398577201190513.png~tplv-a9rns2rl98-image.png?rk3s=25bff839&x-expires=1776934577&x-signature=nUcM5ZGeauCh75nrZD8yV7Enf28%3D',
          date: '2025年4月10日'
        }, {
          title: '侧栏对话支持滚动加载更多',
          tag: '电脑版',
          content: '侧栏历史对话列表优化，现在可以通过滚动加载更多消息。',
          image: 'https://p3-flow-imagex-sign.byteimg.com/ocean-cloud-tos/image_generation/c11f07e04a1d9262fd03606f7a2d30e2_1745398783126629648.png~tplv-a9rns2rl98-image.png?rk3s=25bff839&x-expires=1776934783&x-signature=8uMxUgRgO1Q818AdyNmI35PorkU%3D',
          date: '2025年4月3日'
        }, {
          title: '「深度思考」升级，支持边想边搜',
          tag: '',
          content: '新版「深度思考」功能将推理过程的思维链与搜索深度结合，支持边想边搜。思考过程中，豆包可基于推理多次调用工具、搜索信息，提供更加全面准确的结果。',
          image: 'https://p9-flow-imagex-sign.byteimg.com/ocean-cloud-tos/image_generation/a076534afae506641c4f95b15ac80706_1743425366376087940.png~tplv-a9rns2rl98-image.png?rk3s=25bff839&x-expires=1774961366&x-signature=9ZGfQpgXTgWgatVcLNDAuJzAzDM%3D',
          date: '2025年3月28日'
        }, {
          title: '「AI 云盘」自动保存会议纪要',
          tag: '',
          content: '使用豆包「会议纪要」功能生成的会议记录，现在将自动保存至「AI 云盘」，一站式管理，随时查阅，轻松回溯。',
          image: 'https://p9-flow-imagex-sign.byteimg.com/ocean-cloud-tos/image_generation/0004d4403ceda9fde92503305c683548_1743425886569155545.png~tplv-a9rns2rl98-image.png?rk3s=25bff839&x-expires=1774961886&x-signature=NUBNcsoOMliiI9yQyZN8x%2BRFw8s%3D',
          date: '2025年3月21日'
        }]
      };
    } catch (error) {
      ctx.body = { success: false, error: error.message };
    }
  }
}

// 导出时确保包含新的方法
module.exports = AgentController;